<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/11 13:51
 * Modified Time: 2019/7/11 13:51
 * Version: 2.0
 */

namespace App\Modules\Inventory\Repositories;


use App\Exceptions\AllValidatorException;
use App\Models\GoodsStock;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;

class GoodsStockRepository extends BaseRepository
{
    public function model()
    {
        return GoodsStock::class;
    }

    public function createGoodsStock($store_id,$goods_id,$count=0)
    {
        $data = [
            'store_id' => $store_id,
            'goods_id' => $goods_id,
            'count' => $count
        ];

        return $this->create($data);
    }

    public function stockBuildup($goods_id,$count)
    {
        return $this->findByField('goods_id', $goods_id)
            ->first()
            ->update([
                'count' => DB::raw('count + ' . $count),
                'percent' => DB::raw('percent + ' . $count * 100),
            ]);
    }

    public function reduceStock($goods_id,$count){
        $goods = $this->findByField(['goods_id'=>$goods_id])->first();
        $now_count = $goods->count;
        if($now_count<$count){
            throw new AllValidatorException(['msg'=>'库存量不足']);
        }
        $goods->decrement('percent',$count*100);
        return $goods->decrement('count', $count);
    }

    public function getGoodsStock($goods_id)
    {
        return $this->findByField(['goods_id'=>$goods_id])->first()->percent;
    }
}